package cn.wolfcode.car.business.service.impl;

import cn.wolfcode.car.business.domain.BpmnInfo;
import cn.wolfcode.car.business.mapper.BpmnInfoMapper;
import cn.wolfcode.car.business.query.BpmnInfoQuery;
import cn.wolfcode.car.business.service.IBpmnInfoService;
import cn.wolfcode.car.common.base.page.TablePageInfo;
import cn.wolfcode.car.common.config.SystemConfig;
import cn.wolfcode.car.common.exception.BusinessException;
import cn.wolfcode.car.common.util.Convert;
import com.github.pagehelper.PageHelper;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.image.impl.DefaultProcessDiagramGenerator;
import org.apache.poi.util.IOUtils;
import org.apache.xpath.operations.Mod;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.Collections;
import java.util.Date;
import java.util.List;

@Service
@Transactional
public class BpmnInfoServiceImpl implements IBpmnInfoService {

    @Autowired
    private BpmnInfoMapper bpmnInfoMapper;

    @Autowired
    private RepositoryService repositoryService;


    @Override
    public TablePageInfo<BpmnInfo> query(BpmnInfoQuery qo) {
        PageHelper.startPage(qo.getPageNum(), qo.getPageSize());
        return new TablePageInfo<>(bpmnInfoMapper.selectForList(qo));
    }


    @Override
    public void save(BpmnInfo bpmnInfo) {
        bpmnInfoMapper.insert(bpmnInfo);
    }

    @Override
    public BpmnInfo get(Long id) {
        return bpmnInfoMapper.selectByPrimaryKey(id);
    }


    @Override
    public void update(BpmnInfo bpmnInfo) {
        bpmnInfoMapper.updateByPrimaryKey(bpmnInfo);
    }

    @Override
    public void deleteBatch(String ids) {
        Long[] dictIds = Convert.toLongArray(ids);
        for (Long dictId : dictIds) {
            bpmnInfoMapper.deleteByPrimaryKey(dictId);
        }
    }

    @Override
    public List<BpmnInfo> list() {
        return bpmnInfoMapper.selectAll();
    }

    @Override
    @Transactional
    public void deploy(String path, String bpmnType, String info) throws FileNotFoundException {
        //获取上传文件路径
        File file= new File(SystemConfig.getProfile(),path);
        //部署流程定义
        Deployment deploy = repositoryService.createDeployment()
                .addInputStream(path, new FileInputStream(file))
                .deploy();
        //把流程定义对象
        BpmnInfo bpmnInfo = new BpmnInfo();
        bpmnInfo.setBpmnType(bpmnType);//设置文件类型
        bpmnInfo.setDeploymentId(deploy.getId()); //设置部署ID
        bpmnInfo.setInfo(info); //设置备注信息
        bpmnInfo.setDeployTime(new Date()); //设置创建时间

        //获取流程定义对象
        ProcessDefinition definition = repositoryService.createProcessDefinitionQuery().deploymentId(deploy.getId())
                .singleResult();

        bpmnInfo.setActProcessKey(definition.getKey()); //流程定义Key
        bpmnInfo.setBpmnName(definition.getName()); //Bpmn名称
        bpmnInfo.setActProcessId(definition.getId()); //流程定义ID

        //保存到数据库
        bpmnInfoMapper.insert(bpmnInfo);

    }

    @Override
    public InputStream getResourceByType(String deploymentId, String type) {
        //获取流程定义
        ProcessDefinition definition = repositoryService.createProcessDefinitionQuery().deploymentId(deploymentId)
                .singleResult();
        //判断资源类型
        if ("xml".equalsIgnoreCase(type)) {
            //获取资源名称
           return repositoryService.getResourceAsStream(deploymentId,definition.getResourceName());

        }else {
            //获取bpmn模型
            BpmnModel bpmnModel = repositoryService.getBpmnModel(definition.getId());
            DefaultProcessDiagramGenerator generator = new DefaultProcessDiagramGenerator();
            //根据插件提供的方法,获取图片的输入流
            InputStream inputStream = generator.generateDiagram(bpmnModel, Collections.EMPTY_LIST,
                    Collections.EMPTY_LIST, "微软雅黑", "微软雅黑", "微软雅黑");
            return inputStream;

        }

    }

    @Override
    public void delete(Long id) {
        //获取bpmn对象
        BpmnInfo bpmnInfo = this.get(id);
        //删除数据库的bpmn对象
        bpmnInfoMapper.deleteByPrimaryKey(id);

        //获取流程定义对象
        ProcessDefinition definition = repositoryService.createProcessDefinitionQuery().deploymentId(bpmnInfo.getDeploymentId())
                .singleResult();
        //删除流程定义
        repositoryService.deleteDeployment(bpmnInfo.getDeploymentId(),true);
        //获取资源名称
        String resourceName = definition.getResourceName();
        File file=new File(SystemConfig.getProfile(),resourceName);
        //如果该文件存在,删除服务器的文件
        if (file.exists()){
            file.delete();
        }

    }

    @Override
    public BpmnInfo queryByType(String type) {
        return bpmnInfoMapper.queryByType(type);
    }
}
